package controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.TeamMemberItemBean;
import sql.TeamMemberDao;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);		
		session.setAttribute("currentUser", null);
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
	
		TeamMemberDao teamMemberDao = new TeamMemberDao();
		
		try {
			TeamMemberItemBean teamMemberItemBean = teamMemberDao.getTeamMemberInfo(username, password);
			String url = "";

			if (teamMemberItemBean == null) {
				request.setAttribute("errorMsg", "Invalid email or password. Please try again!");
				url = "index.jsp";

				RequestDispatcher dispatcher = request.getRequestDispatcher(url);
				dispatcher.forward(request, response);
			} else {
				session.setAttribute("currentUser", teamMemberItemBean);
				if (teamMemberItemBean.getProjectId() == 0) {
					url = "Projects.jsp";
				}
				else {
					url = "Sprints.jsp";
				}
				response.sendRedirect(url);
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

}
